package com.example.base.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.base.app.AppClassService;
import com.example.base.config.PageData;
import com.example.base.excetion.GlobalExcetion;
import com.example.base.job.AppJobModelService;
import com.example.base.job.IJob;
import com.example.base.job.JobAppMap;
import com.example.base.system.domain.SysApp;
import com.example.base.system.domain.SysJob;
import com.example.base.system.domain.vo.SysAppVo;
import com.example.base.system.SysAppService;
import com.example.base.system.service.SysJobService;
import com.example.base.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.base.limit.IPRateLimit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author X.I.O
 * @since 2024-02-23
 */
@Slf4j
@RestController
@Api(tags = {"系统app的服务类"})
@RequestMapping("/sys-app")
public class SysAppController  {

        @Autowired
        private SysJobService sysJobService;

        @Autowired
        private SysAppService sysAppService;

        @Autowired
        private AppClassService appClassService;

        @Autowired
        private JobAppMap jobAppMap;

        @GetMapping("/getappjobclass")
        public JSONObject getAppJobClassList(@RequestParam("appName")String appName){
                if(appName==null){
                        return Result.errorInfo("appName不得为空");
                }
                List<IJob> iJobList=jobAppMap.getIJobList(appName);
                List<SysJob> list=sysJobService.getSysJobAppName(appName);
                List<String> clsList=new ArrayList<>();
                if(list!=null){
                    clsList=list.stream().map(SysJob::getAppClass).collect(Collectors.toList());
                }
                JSONArray array=new JSONArray();
                if(iJobList!=null && iJobList.size() >0){
                    for(IJob e:iJobList){
                        if(!clsList.contains(e.getClass().getName())){
                             JSONObject object=new JSONObject();
                             object.put("key",e.getClass().getName());
                             object.put("label",e.getClass().getName()+"/"+e.getDesc());
                             array.add(object);
                        }
                    }
                }
                return Result.successInfo(array);
        }


        @PostMapping("/saveorupdate")
        @IPRateLimit(name = "SysApp-saveorupdate",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的新增/更新接口",notes = "的新增接口")
        public JSONObject save(@RequestBody @Validated SysAppVo sysAppVo) throws GlobalExcetion {
                sysAppService.saveOrUpdateSysApp(sysAppVo);
                return Result.successInfo("操作成功");
        }

        @GetMapping("/getappoption")
        public JSONObject getAppOption(){
            List<SysApp> sysAppList=sysAppService.getSysAppList();
            JSONArray array=new JSONArray();
            if(sysAppList!=null){
                sysAppList.forEach((e)->{
                      JSONObject object=new JSONObject();
                      object.put("key",e.getAppInfo().getAppName());
                      object.put("label",e.getAppInfo().getAppDesc());
                      array.add(object);
                });
            }
            return Result.successInfo(array);
        }

        @PostMapping("upload")
        public JSONObject uploadFile(MultipartFile file) throws IOException {
                String path=sysAppService.getAppPath();
                String fileName=file.getOriginalFilename();
                File outPath=new File(path+File.separator+fileName);
                file.transferTo(outPath.toPath());
                return Result.successInfo("上传成功");
        }


        @PostMapping("/save")
        @IPRateLimit(name = "SysApp-save",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的新增接口",notes = "的新增接口")
        public JSONObject save(@RequestBody SysApp sysApp) throws GlobalExcetion{
                 sysAppService.saveSysApp(sysApp);
                 return Result.successInfo("保存成功");
        }


        @PostMapping("/update")
        @IPRateLimit(name = "SysApp-update",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的更新接口",notes = "的更新接口")
        public JSONObject update(@RequestBody SysApp sysApp) throws GlobalExcetion{
                sysAppService.updateSysAppById(sysApp);
                return Result.successInfo("更新成功");
        }



        @DeleteMapping("/delbyid")
        @IPRateLimit(name = "SysApp-del",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的删除接口",notes = "的删除接口")
        public JSONObject delete(@RequestParam("id") Serializable id) throws GlobalExcetion{
                boolean flag = sysAppService.removeById(id);
                if(flag){
                        return Result.successInfo("删除成功");
                }else {
                        return Result.errorInfo("删除失败");
                }
        }

        @PostMapping("/del/batch")
        @IPRateLimit(name = "SysApp-delbatch",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的批量删除接口",notes = "的批量删除接口")
        public JSONObject deleteBatch(@RequestBody List<Integer> ids) throws GlobalExcetion {
                boolean flag =  sysAppService.removeByIds(ids);
                if(flag){
                        return Result.successInfo("删除成功");
                }else {
                        return Result.errorInfo("删除失败");
                }
        }

        @GetMapping("/getall")
        @IPRateLimit(name = "SysApp-getall",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的获取全部接口",notes = "的获取全部接口")
        public JSONObject findAll() throws GlobalExcetion {
                List<SysApp> list= sysAppService.list();
                return Result.successInfo(list);
        }

        @GetMapping("/getbyid")
        @IPRateLimit(name = "SysApp-getid",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的获取一个接口",notes = "的获取一个接口")
        public JSONObject findOne(@RequestParam("id") Serializable id) throws GlobalExcetion {
                SysApp data= sysAppService.getById(id);
                return Result.successInfo(data);
        }

        @GetMapping("/page")
        @IPRateLimit(name = "SysApp-page",msg = "系统检测到ip异常访问行为，已暂停访问")
        @ApiOperation(value = "的分页接口",notes = "的分页接口")
        public JSONObject findPage(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                        @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize) throws GlobalExcetion {
                IPage<SysApp> data=sysAppService.page(page, pageSize);
                PageData pageData=new PageData(data.getTotal(),page,pageSize,data.getRecords());
                return Result.successInfo(pageData);
        }


}

